package org.mili.ticketeer.report;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.mili.core.templating.TemplateStore;
import org.mili.ticketeer.dto.Contact;
import org.mili.application.service.ServiceException;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

public class MeetingGenerator extends AbstractGenerator {
    public MeetingGenerator(ReportEngine reportEngine, TemplateStore templateStore) {
        super(reportEngine, templateStore);
    }

    public void generate() throws IOException, ServiceException {
        StringBuilder s = new StringBuilder();
        StringBuilder s1 = new StringBuilder();
        String temp1 = templateStore.get("meetings_Member");
        String temp2 = templateStore.get("meetings_Item");
        for(Contact contact : reportEngine.getContacts()) {
            if (!contact.isActive()) {
                continue;
            }
            s1.setLength(0);
            Set<Integer> meetings = reportEngine.getCurrentMeetings(contact);
            System.out.println("meetings: " + meetings);
            for(int i = 0; i < 12; i ++) {
                int month = i + 1;
                boolean check = meetings.contains(month);
                s1.append(temp2
                        .replace("${char}", check ? "X" : "&nbsp;")
                );
            }
            s.append(temp1
                    .replace("${Item}", s1)
                    .replace("${firstname}", contact.getFirstName())
                    .replace("${lastname}", contact.getLastName())
                    .replace("${sex}", reportEngine.printSex(contact.getSex()))
            );
        }
        SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
        FileUtils.writeStringToFile(new File("./tmp/out/anwesenheit.html"),
                templateStore.get("meetings_Main")
                        .replace("${Member}", s)
                        .replace("${date}", format.format(new Date()))
                        .replace("${title}", "Anwesenheit")
        );
    }

    private String printEmail(String email) {
        if (StringUtils.isEmpty(email)) {
            return email;
        }
        return "E-Mail:&nbsp;" + email;
    }

}
